//@author A0101119Y
#include "GCalAuthHandler.h"

using namespace Twentyfifth;
using namespace std;


const string GCalAuthHandler::GCALCMD_LOGIN = "login";
const string GCalAuthHandler::GCALCMD_INFO = "info";
const string GCalAuthHandler::GCALCMD_LOGOUT = "logout";
const string GCalAuthHandler::LABEL_EMAIL_ADDRESS = "email";
const string GCalAuthHandler::MSG_ERROR_ALREADY_LOGGED_IN = "You are already logged in as %s. Please log out first.";
const string GCalAuthHandler::MSG_INFORMATION_LOGGED_IN = "You are logged in as %s.";
const string GCalAuthHandler::MSG_INFORMATION_NOT_LOGGED_IN = "You are not logged in.";
const string GCalAuthHandler::MSG_SUCCESS_LOGOUT = "Logout successful. All data cleared.";
const string GCalAuthHandler::PLACEHOLDER_STRING = "%s";

Status GCalAuthHandler::login() {
	Status s;
	GCalVariableMgr varmgr;
	if (isLoggedIn()) {
		s.code = Status::ERR_OTHER;
		string emailAddress = varmgr.getValue(LABEL_EMAIL_ADDRESS);
		string errorMsg = MSG_ERROR_ALREADY_LOGGED_IN;
		size_t posPlaceholder = errorMsg.find(PLACEHOLDER_STRING);
		errorMsg.replace(posPlaceholder, PLACEHOLDER_STRING.length(), emailAddress);
		s.desc = errorMsg;
	} else {
		s = accrequestagent.firstAuthenticate();
	}
	return s;
}

Status GCalAuthHandler::logout() {
	Status s;
	GCalVariableMgr varmgr;
	varmgr.clearAll();
	s.code = Status::OK;
	s.desc = MSG_SUCCESS_LOGOUT;
	return s;
}

Status GCalAuthHandler::info() {
	Status s;
	GCalVariableMgr varmgr;
	s.code = Status::OK;
	if (isLoggedIn()) {
		string emailAddress = varmgr.getValue(LABEL_EMAIL_ADDRESS);
		string message = MSG_INFORMATION_LOGGED_IN;
		size_t posPlaceholder = message.find(PLACEHOLDER_STRING);
		message.replace(posPlaceholder, PLACEHOLDER_STRING.length(), emailAddress);
		s.desc = message;
	} else {
		s.desc = MSG_INFORMATION_NOT_LOGGED_IN;
	}
	return s;
}

bool GCalAuthHandler::isLoggedIn() {
	GCalVariableMgr varmgr;
	return varmgr.exists(LABEL_EMAIL_ADDRESS);
}
